<?php

class QuickTest {

    public $s = null;
    public $smarty = null;

    public function __construct() {
        include_once($_SERVER['DOCUMENT_ROOT'] . "/RecJP/class/class.SqliteHelper.php");
        include_once($_SERVER['DOCUMENT_ROOT'] . "/RecJP/class/Model/Model.userMemory.php");
        include_once($_SERVER['DOCUMENT_ROOT'] . "/RecJP/class/DAL/DAL.danciOperator.php");
        include_once($_SERVER['DOCUMENT_ROOT'] . "/RecJP/class/DAL/DAL.userMemory.php");
        include_once($_SERVER['DOCUMENT_ROOT'] . "/RecJP/inc/smarty_inc.php");
        include_once($_SERVER['DOCUMENT_ROOT'] . "/RecJP/Common.php");
        $this->smarty = getSmarty();
        $this->s = new SqliteHelper();
    }

    public function GetNextFromListFromSession() {
        $list = $_SESSION["recitlist"];
        //Common::LogLinetxt($list, 'file11.txt');
        if ($list == null || 0 == count($list)) {
            return -1;
            die();
        }
        $sum = 0;
        $listPoint = array(0);
        foreach ($list as $value) {
            $sum+=$value;
            array_push($listPoint, $sum);
        }

        $num = mt_rand(0, $sum);
        for ($i = 0; $i < count($listPoint) - 1; $i++) {
            if ($num >= $listPoint[$i] && $num <= $listPoint[$i + 1]) {
                return array_keys($list)[$i]; //第i项的key值，即wordid
            }
        }
        echo "can't be here";
    }

    //设置选项，根据是否答对，更新答题错误率等数据
    public function SetOptions($wordid, $right) {
        $userMemory = new Model_userMemory();
        $userMemory->userid = $_SESSION["userid"];
        $userMemory->wordid = $wordid;
        $userMemory->username = $_SESSION['username'];

        $result = Dal_userMemory::select($userMemory);
        if (count($result) > 0) {
            $userMemory->wordid = $result[0]["wordid"];
            $userMemory->userid = $result[0]["userid"];
            $userMemory->username = $result[0]["username"];
            $userMemory->memory = $result[0]["memory"];
            $userMemory->testCount = $result[0]["testCount"] + 1;
            if ($right == false) {
                $userMemory->testerrorCount = $result[0]["testerrorCount"] + 1;
                self::UpdateCookie_TestWrongCount($userMemory);
            } else {
                $userMemory->testerrorCount = $result[0]["testerrorCount"];
                self::UpdateCookie_TestRightCount($userMemory);
            }
            $userMemory->errorRate = $userMemory->testerrorCount / $userMemory->testCount;
            $result = Dal_userMemory::update($userMemory);
        } else {
            $userMemory->memory = 0;
            $userMemory->testCount = 1;
            if ($right == false) {
                $userMemory->testerrorCount = 1;
                self::UpdateCookie_TestWrongCount($userMemory);
            } else {
                $userMemory->testerrorCount = 0;
                self::UpdateCookie_TestRightCount($userMemory);
            }
            $userMemory->errorRate = $userMemory->testerrorCount / $userMemory->testCount;
            $result = Dal_userMemory::insert($userMemory);
        }

        /*
          if (isset($_SESSION["recitlist"]) == false || isset($_SESSION["recitlist"][$userMemory->wordid])) {
          if (isset($_SESSION["recitlist"]) == true && $_SESSION["accordingby"] == 0) {//根据记忆度排
          $_SESSION["recitlist"][$userMemory->wordid] = (int) ($userMemory->errorRate * 100);
          }
          }
         */

        if (isset($_SESSION["recitlist"][$userMemory->wordid])) {
            $_SESSION["recitlist"][$userMemory->wordid] = (int) ($userMemory->errorRate * 100) < 1 ? 1 : (int) ($userMemory->errorRate * 100);
        }

        return $userMemory;
    }

    public function GetOptions($wordid, &$correctItem) {
        $Options = Dal_danciOperator::GetRandomOption($wordid, 3) ;
        foreach ($Options as $key => $value) {
            if ($value["wordid"] == $wordid) {
                $Options[$key]["right"] = "1";
                $correctItem = $Options[$key]; //正确项
            } else {
                $Options[$key]["right"] = "0";
            }
        }

        //乱序
        $num = 1;
        $RandOptions = array();
        while (count($Options) > 0) {
            $num = mt_rand(1, 100);
            $index = fmod($num, count($Options)); //求余
            $RandOptions[] = $Options[$index];
            array_splice($Options, $index, 1);
        }
        return $RandOptions;
    }

    public function GetWordBywid($wordid) {
        return Dal_danciOperator::GetWordBywid($wordid);
    }

    public function GetWordListWithErrorrate($lessonidLst, $bid) {
        $instr = "-1";
        if (count($lessonidLst) == 1 && $lessonidLst[0] == 0) { //如果只有1个0，说明未选课程，系统自动随机抽取50个单词
            $wordidLst = Dal_danciOperator::GetRandomWordidInBook(50, $bid);

            foreach ($wordidLst as $value) {
                $instr.=",$value";
            }

            $sql = "select *,danci.wordid from danci left join userMemory on 
                danci.wordid=userMemory.wordid 
                where userMemory.userid=:userid and danci.wordid in ($instr)";
        } else {
            foreach ($lessonidLst as $value) {
                $instr.=",$value";
            }

            $sql = "select *,danci.wordid from danci left join userMemory on 
                (danci.wordid=userMemory.wordid and userMemory.userid=:userid)
                where  bookid=:bookid and danci.lesson in ($instr)";
        }

        $p = array(":userid" => $_SESSION["userid"], ":bookid" => $bid);
        $result = $this->s->Query($sql, $p);
        $GetWordListWithErrorrate = array();
        foreach ($result as $key => $value) {
            if (isset($_SESSION["recitlist"]) == true && $_SESSION["accordingby"] == 1) {//根据记忆度排
                $memory = Common::is_empty($value["memory"], 0);
                if ($memory > 5) {
                    $memory = 5;
                }
                $GetWordListWithErrorrate[(string) $value["wordid"]] = 6 - $memory;
            } else {//根据出错率排
                $errorRate = (int) ($value["errorRate"] * 100);
                if (empty($value["errorRate"])) {
                    $errorRate = 99;
                }
                $GetWordListWithErrorrate[(string) $value["wordid"]] = $errorRate;
            }
        }
        return $GetWordListWithErrorrate;
    }

    public function display($Options, $correctItem, $quizType) {
        $this->smarty->assign("correctItem", $correctItem);
        $this->smarty->assign("Options", $Options);

        if (empty($quizType)) {
            $quizType = mt_rand(1, 2);
        }
        $this->smarty->assign("quizType", $quizType);
        $this->smarty->display('quickTest.tpl.htm');

        self::RemoveCookieInfo();
    }

    public function UpdateCookie_TestRightCount($userMemory) {
        if (isset($_COOKIE['TestedAndRightList'])) {
            $TestedAndRightList = $_COOKIE['TestedAndRightList'];
        }

        //for test
        //self::RemoveOneElementFromSession($userMemory->wordid);
        if (isset($TestedAndRightList[$userMemory->wordid])) {//设置做对次数+1
            $TestedAndRightCount = $TestedAndRightList[$userMemory->wordid] + 1;
            SetCookie("TestedAndRightList[$userMemory->wordid]", $TestedAndRightCount, time() + 3600);

//            if ($TestedAndRightCount >= 2 && errorRate <= 0.1) {//测试2次以上，错误率在0.1以下，该单词从测试列表删除
//                self::RemoveOneElementFromSession($userMemory->wordid);
//            } else 
                if ($TestedAndRightCount >= 4 && $userMemory->errorRate < 0.3) {//测试4次以上，错误率在0.3以下，该单词从测试列表删除
                self::RemoveOneElementFromSession($userMemory->wordid);
            } else if ($TestedAndRightCount >= 8) {//测试8次以上，该单词从测试列表删除
                self::RemoveOneElementFromSession($userMemory->wordid);
            }
        } else {
            SetCookie("TestedAndRightList[$userMemory->wordid]", 1, time() + 3600);
        }
    }

    public function UpdateCookie_TestWrongCount($userMemory) {
        if (isset($_COOKIE['TestedAndWrongList'])) {
            $TestedAndWrongList = $_COOKIE['TestedAndWrongList'];
        }
        //for test
        //self::RemoveOneElementFromSession($userMemory->wordid);
        if (isset($TestedAndWrongList[$userMemory->wordid])) {//设置做错次数+1
            $TestedAndWrongCount = $TestedAndWrongList[$userMemory->wordid] + 1;
            SetCookie("TestedAndWrongList[$userMemory->wordid]", $TestedAndWrongCount, time() + 3600);
        } else {
            SetCookie("TestedAndWrongList[$userMemory->wordid]", 1, time() + 3600);
        }
    }

    public function GetCookie_TestRightCount($wordid) {
        if (isset($_COOKIE['TestedAndRightList'])) {
            $TestedAndRightList = $_COOKIE['TestedAndRightList'];
            return $TestedAndRightList[$wordid];
        } else {
            return 0;
        }
    }

    //答对的单词，从session中移除
    public function RemoveOneElementFromSession($wid) {
        if (isset($_SESSION["recitlist"]) == false || count($_SESSION["recitlist"]) == 0) {
            return -1;
            //die();
        } else {
            $list = $_SESSION["recitlist"];
            unset($list[$wid]);
            $_SESSION["recitlist"] = $list;
        }
    }

    public function RemoveCookieInfo() {
        if (isset($_COOKIE['TestedAndWrongList'])) {
            foreach ($_COOKIE['TestedAndWrongList'] as $key => $value) {
                SetCookie("TestedAndWrongList[$key]", NULL);
            }
        }

        if (isset($_COOKIE['TestedAndRightList'])) {
            foreach ($_COOKIE['TestedAndRightList'] as $key => $value) {
                SetCookie("TestedAndRightList[$key]", NULL);
            }
        }
    }

}